<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="addForm">添加清单页</el-button>
      <el-button @click="deleteForm">删除清单页</el-button>
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>

    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div class="title">
        <div class="biaotididian">{{ agencyName }}</div>
        <div class="biaoti">查封（扣押）决定书</div>
      </div>
      <div class="foreword1">
        <input v-model="form.a1" :resize="'none'" autosize maxlength="4" class="inputStyle1"
          style="width: 80px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea">
        <span>（</span>
        <reference-select style="width: 5mm;margin-bottom: 4px" v-model="form.referenceValue"
          class="InvestigatorSelectReplace" />
        <span>）查（扣）决字[</span>
        <input v-model="form.a2" :resize="'none'" autosize maxlength="4" class="areaInputStyle"
          style="width: 40px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
          oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
        <span>]第</span>
        <input v-model="form.a3" :resize="'none'" autosize maxlength="5" class="areaInputStyle"
          style="width: 50px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
          oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
        <span>号</span>
      </div>
      <div class="tableStyle1">
        <div class="writ-height">
          <div style="display: inline-block; position: relative;">
            <span>当事人：</span>
            <privy-info-select-return-array v-model="form.unitName" v-model:isSelected="form.isUnit" :isTable="false"
              return-fields="A(B)" :return-array-template="[
                { name: 'companyAddress', field: 'E' },
              ]" :rowConfig="unitNameConfig" @select="selectUnitUpdateData">
            </privy-info-select-return-array>
          </div>
        </div>
        <div class="writ-height">
          <span>地&nbsp;&nbsp;址：</span>
          <CrossRowInput v-model:value="form.companyAddress" :line-config="companyAddressConfig" />
        </div>
        <div style="height: 490px; line-height: 30px;">
          <span>&nbsp;&nbsp;&nbsp;&nbsp;因你</span>
          <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
          <LawsAndRegulationsSelect v-model:illegalActText="form.a6" v-model:returnIllegalTermsString="form.a7"
            v-model:returnIllegalBasisString="form.a8" width="100px" />
          <span>的行为，涉嫌违反了</span><span v-if="form.a7" class="span-underline">{{ form.a7 }}</span><span v-else
            class="span-underline">&nbsp;&nbsp;</span><span>的规定。根据《中华人民共和国行政强制法》第二十二条至第二十八条等规定，对本决定书附件所列的有关场所、设施或物品予以查封（扣押）。查封（扣押）期限自</span>
          <editable-textarea :text="form.date1" param-type="YYYYMMDD1"
            @send-to-parent="receiveFromChild" /><span>至</span>
          <editable-textarea :text="form.date2" param-type="YYYYMMDD2"
            @send-to-parent="receiveFromChild" /><span>止。如因检测、检验、检疫或者技术鉴定需要顺延期限的，或因情况复杂依法需要延长期限的，本机关将依法作出延期决定。在查封（扣押）期限内，不得损毁、销毁或转移。</span>
          <br><span>&nbsp;&nbsp;&nbsp;&nbsp;如你</span>
          <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
          <span>不服本决定，可以在收到本决定书之日起60日内向</span>
          <CrossRowInput v-model:value="form.a9" :line-config="a9Config"></CrossRowInput>
          <span>申请行政复议；也可以在6个月内直接向</span>
          <input v-model="form.a10" :resize="'none'" autosize maxlength="15" class="inputStyle1"
            style="width: calc(15 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
          <span>人民法院提起行政诉讼。</span>
        </div>
        <div class="writ-height" style="margin-top: 20px; ">&nbsp;&nbsp;&nbsp;&nbsp;附：查封（扣押）清单</div>
        <div style="text-align: right; margin-top: 20px; margin-bottom: 50px;">
          <div class="seal-container">
            <span class="seal-name" v-html="sealName"></span>
            <div class="delivery-agency-div" :class="{ 'official-seal-display': isDisplay }">
              <editable-textarea :text="form.date3" param-type="YYYYMMDD3" @send-to-parent="receiveFromChild" />
              <img class="official-seal" src="../../assets/tupian.png" alt="Image">
            </div>
          </div>
        </div>
        <div style="line-height: 30px;">
          <span>联&nbsp;系&nbsp;人：</span><input v-model="form.a11" :resize="'none'" autosize maxlength="6"
            class="inputStyle1" style="width: calc(6 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
          <span>联系地址：</span><input v-model="form.a12" :resize="'none'" autosize maxlength="16" class="inputStyle1"
            style="width: calc(16 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
          <br><span>联系电话：</span><input v-model="form.a13" :resize="'none'" autosize maxlength="12" class="inputStyle1"
            style="width: calc(6 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea"
            oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
          <span>邮政编码：</span><input v-model="form.a14" :resize="'none'" autosize maxlength="16" class="inputStyle1"
            style="width: calc(16 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
        </div>
      </div>
      <!-- 清单 -->
      <div v-for="(item, index) in form.inventoryTable" :key="index" class="page-break">
        <div class="title">
          <div class="biaotididian">查封（扣押）清单</div>
        </div>
        <table class="tableStyle">
          <colgroup>
            <col width="7%">
            <col width="19%">
            <col width="19%">
            <col width="19%">
            <col width="19%">
            <col width="17%">
          </colgroup>
          <thead>
            <tr>
              <th style="height: 40px">编号</th>
              <th>名称</th>
              <th>数量/单位</th>
              <th>规格</th>
              <th>型号</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item1, index1) in item" :key="index1">
              <td height="80px">
                <el-input v-model="item1.number" :resize="'none'" autosize maxlength="6" class="areaInputStyle"
                  type="textarea" ref="inputRef6">
                </el-input>
              </td>
              <td>
                <el-input v-model="item1.name" :resize="'none'" autosize maxlength="18" class="areaInputStyle"
                  type="textarea" ref="inputRef6">
                </el-input>
              </td>
              <td>
                <el-input v-model="item1.quantity" :resize="'none'" autosize maxlength="18" class="areaInputStyle"
                  type="textarea" ref="inputRef6">
                </el-input>
              </td>
              <td>
                <el-input v-model="item1.specifications" :resize="'none'" autosize maxlength="18" class="areaInputStyle"
                  type="textarea" ref="inputRef6">
                </el-input>
              </td>
              <td>
                <el-input v-model="item1.model" :resize="'none'" autosize maxlength="18" class="areaInputStyle"
                  type="textarea" ref="inputRef6">
                </el-input>
              </td>
              <td>
                <el-input v-model="item1.remark" :resize="'none'" autosize maxlength="15" class="areaInputStyle"
                  type="textarea" ref="inputRef6">
                </el-input>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js";
import PrivyInfoSelectReturnArray from "@/views/template/PrivyInfoSelectReturnArray";
import LawsAndRegulationsSelect from "@/views/template/LawsAndRegulationsSelect";
import CrossRowInput from "@/views/template/CrossRowInput";
import ReferenceSelect from "@/views/template/ReferenceSelect";

export default {
  components: {
    LawsAndRegulationsSelect,
    EditableTextarea,
    CrossRowInput,
    ReferenceSelect,
    PrivyInfoSelectReturnArray,
  },

  data() {
    return {
      agencyName: agencyName,
      sealName: sealName,
      form: {
        inventoryTable: [[
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
          { number: '', name: '', quantity: '', specifications: '', model: '', remark: '' },
        ]],
        isUnit: true,
      },
      status: '', //当前文书的状态
      isPdfExport: false, //控制打印样式
      isDisplay: true, //控制官方印章的显示
      unitNameConfig: {
        firstLine: { chars: 28 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 0 * 2 }
      },
      companyAddressConfig: {
        firstLine: { chars: 28 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 0 * 2 }
      },
      a9Config: {
        firstLine: { chars: 2 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 18 * 2 }
      },

    }
  },

  created() {
    window.parent.getTemplateData((data, status) => {
      this.form = data;
      this.status = status;
    })
    window.postForm = () => {
      this.postForm();
    }
  },

  mounted() {
    window.parent.changeTemplateDow();
  },

  methods: {
    // 添加页
    addForm() {
      if (!Array.isArray(this.form.inventoryTable)) {
        this.form.inventoryTable = []; // 重置为数组
      }
      // 添加新页（包含10个空行）
      this.form.inventoryTable.push(Array(10).fill().map(() => ({
        number: '', name: '', quantity: '', specifications: '', model: '', remark: ''
      })));
    },
    // 删除页
    deleteForm() {
      // 确保至少保留一页
      if (this.form.inventoryTable.length > 1) {
        this.form.inventoryTable.pop();
      } else {
        this.$message.warning('至少保留一页');
      }
    },
    // 导出为pdf
    exportPDF() {
      if (this.status !== '4') {
        this.isDisplay = false
      }
      this.savePDF()
        .then((blob) => {

          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `查封（扣押）决定书.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                this.isDisplay = true;
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            this.isDisplay = true;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '查封（扣押）决定书.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },
    //选择日期时间
    receiveFromChild(data, type) {
      const TypeMap = {
        'YYYYMMDD1': 'date1',
        'YYYYMMDD2': 'date2',
        'YYYYMMDD3': 'date3',
      };
      if (TypeMap[type]) {
        this.form[TypeMap[type]] = data;
      }
    },
    // 切换单位删除线
    switchUnitDelLine() {
      this.form.isUnit = !this.form.isUnit
    },
    // 选择单位
    selectUnitUpdateData(data) {
      data.forEach(item => {
        this.form[item.name] = item.value;
      })
    },
  }
}
</script>

<style scoped>
.official-seal {
  /* 公章隐藏，在打印时显示，具体打印会，print.css有显示样式。 */
  display: none;
  width: 4.2cm;
  height: 4.2cm;
  z-index: 20;

  /* 定位 */
  position: absolute;
  bottom: -20px;
  right: -10px;
}


:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
  white-space: pre-wrap;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
